<template>
  <div class="app-container">
    <el-row :gutter="10">
      <el-button type="success" icon="el-icon-plus" size="mini" @click="handleAdd">添加</el-button>
    </el-row>


    <el-table v-loading="loading" :data="bannerList" >
      <template slot="empty">
        <el-empty :image-size="100"  description='暂无数据'></el-empty>
      </template>
      <el-table-column label="bannerId" align="center" prop="bannerId" />
      <el-table-column label="banner标题" align="center" prop="bannerName" />
      <el-table-column label="banner地址" align="center" prop="bannerUrl" >
        <template slot-scope="scope">
          <el-image
            style="width: 160px; height: 90px"
            :src="scope.row.bannerUrl"
            fit="cover"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="banner标题" prop="bannerName">
          <el-input v-model="form.bannerName" type="textarea" placeholder="请输入内容"  />
        </el-form-item>
        <el-form-item label="baner地址" prop="bannerUrl">
          <el-upload
            ref="upload"
            :before-upload="beforeUpload"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="primary" @click="handleUpload">上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {addBanner, delBanner, getBanner, getBannerList, updateBanner} from "@/api/business/elderlyapartment";
  import {fileUpload} from "@/api/business/elderInfo";

export default {
  name: "Records",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      bannerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bannerName: [
          { required: true, message: 'banner标题不能为空', trigger: 'blur' },
        ],
        bannerUrl: [
          { required: true, message: 'url不能为空', trigger: 'blur' }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.loading = true;
      getBannerList().then(response => {
        this.bannerList = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        bannerId: null,
        bannerName: null,
        bannerUrl: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加首页轮播图";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.bannerId
      console.log(id)
      getBanner(id).then(response => {
        this.form = response;
        this.open = true;
        this.title = "修改首页轮播图";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.bannerId != null) {
            updateBanner(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBanner(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.bannerId;
      this.$modal.confirm('是否确认删除该轮播图？').then(function() {
        return delBanner(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    beforeUpload(file) {
      // 处理上传文件之前的逻辑，例如限制文件类型和大小等
      // ...省略相关代码...
      console.log(file)
      const isLt2M = file.size / 1024 / 1024 < 2;
      const isImage = file.type.startsWith('image/');

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }

      return isImage && isLt2M;// 返回 true 以继续上传文件
    },
    //文件上传
    handleUpload() {
      const uploadComponent = this.$refs.upload; // 引用上传组件
      const file = uploadComponent.uploadFiles[0]; // 获取选择的文件
      if (file) {
        // 构造 FormData 对象并添加文件参数
        const formData = new FormData();
        formData.append('file', file.raw); // 添加文件参数，注意使用 file.raw 获取原始文件对象
        //调用接口
        console.log(formData);
        fileUpload(formData).then(response => {
          // 处理响应结果
          this.form.bannerUrl = response;
          this.$modal.msgSuccess("上传成功!");
          console.log(response)
        }).catch(error => {
          // 处理错误
          this.$modal.msgError("上传失败!");
        });
      } else {
        // 处理未选择文件的情况
        this.$modal.msgWarning("请选择文件后上传");
      }
    },
  }
};
</script>
